package com.qf.om.filter;

import com.qf.om.entity.Admin;
import com.qf.om.myutils.PropertiesUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class Filter010Login implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        System.out.println("登录过滤器触发！");
        //强制类型转换 请求和响应
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //获得拦截的url
        String uri = req.getRequestURI();
        Admin admin  = (Admin) req.getSession().getAttribute("login_user");
        if (admin!=null){
            filterChain.doFilter(req,resp);
        }else {
             String nologin = PropertiesUtils.getProperties("nologin");
             if (nologin!=null){
                 String[] res=nologin.split("\\|");
                 for (String re : res) {
                     //如果连接的路径的末尾包含properties的内容 例如：http://localhost:8080/login.jsp
                     if (uri.endsWith(re)) {
                         //说明当前的资源可以不登录就访问
                         filterChain.doFilter(req, resp);
                         return;
                     }
                 }

             }
             //当没有登录且路径不包含properties的内容时候需要直接跳转到login.jsp
            resp.sendRedirect("login.jsp");
        }

    }
    

    @Override
    public void destroy() {

    }
}
